import threading

import pyttsx3
import tkinter as tk
import time
import tkinter.messagebox

engine = pyttsx3.init()


def say():
    engine.setProperty('voice', 'zh')
    text = edit.get('0.0', 'end')
    engine.setProperty('rate', scale.get())
    engine.say(text, 'fox')
    engine.runAndWait()


def save_file():
    file = f'{int(time.time())}.mp3'
    engine.save_to_file(edit.get('0.0', 'end'), file)
    engine.runAndWait()
    tkinter.messagebox.showinfo('文件保存成功：', file)


def thread_it(func, *args):
    '''将函数打包进线程'''
    # 创建
    t = threading.Thread(target=func, args=args)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()



window = tk.Tk()
window.geometry('400x500')
window.title("文字转语音助手")
window.resizable(width=False, height=False)
edit = tk.Text(window, height=15, width=40,
               highlightcolor='blue', bd=1,
               highlightthickness=1)
edit.pack(pady=25)
scale = tk.Scale(window, bg='pink', fg='red',
                 length=300, label='语速控制：',  # 设置显示的标签
                 from_=0, to=300,  # 设置最大最小值
                 # 注意设置最大值的属性不是'from'，而是'from_'，这是因为python中已经有了from关键字啦
                 resolution=1,  # 设置步距值
                 orient=tk.HORIZONTAL,  # 设置水平方向
                 )
scale.set(163)
scale.pack(pady=4)
button = tk.Button(window, fg='blue', font=('仿宋', 15),
                   bg='orange', bd=5, width=35, text='试 听',
                   command=lambda: thread_it(say))
button.pack(pady=15)
button1 = tk.Button(window, fg='blue', font=('仿宋', 15),
                    bg='pink', bd=5, width=35, text='保 存',
                    command=lambda: thread_it(save_file))
button1.pack(pady=3)
window.mainloop()
